﻿using AutoMapper;
using MediatR;
using Traceability_2203.Common.Domains;
using Traceability_2203.Common.Dtos;
using Traceability_2203.Common.Infrastructure.Interfaces;
using Traceability_2203.Enum;

namespace Traceability_2203.Bais.Api.Application.Commands.User
{
    public class UserCreateHandler : IRequestHandler<UserCreateCommand, Result>
    {
        private readonly IBaseRepository<Users> userRepository;
        private readonly ILogger<UserCreateHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userBaseRepository">用户仓储</param>
        public UserCreateHandler(IBaseRepository<Users> userRepository,
            ILogger<UserCreateHandler> logger,
            IMapper mapper)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //使用AutoMapper 将command入参 转换为实体
                Users user = mapper.Map<Users>(request);
                var res = await userRepository.Add(user);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                }
            }
            catch (Exception ex)
            {
                logger.LogError("【新增用户异常】:" + ex.Message);
                result.Msg = "新增失败";
            }
            finally
            {
                //总是执行
                //记录操作日志
                logger.LogInformation("xx用户添加了一个新用户");
            }
            return result;
        }
    }
}
